package com.naiterui.ehp.bs.file.api.aspect;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpHeaders;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.naiterui.ehp.bp.support.utils.IpUtil;
import com.naiterui.ehp.bs.file.api.bo.FileHeaderBO;
import com.naiterui.ehp.bs.file.api.bo.FileParamBO;

import lombok.extern.slf4j.Slf4j;

/**
 * 文件内部请求切面
 * 
 * @author luao
 * @date 2021/9/13 10:47 上午
 **/
@Slf4j
@Component
@Aspect
public class FileRequestHeaderAspect {

    private final String POINT_CUT = "execution(public * com.naiterui.ehp.bs.file.api.feign.FileFeignClient.*(..))";

    @Pointcut(POINT_CUT)
    public void pointCut() {}

    @Before(value = "pointCut()")
    public void before(JoinPoint joinPoint) {
        // 获取目标方法参数信息
        Object[] args = joinPoint.getArgs();
        ServletRequestAttributes requestAttributes =
            (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes == null ? null : requestAttributes.getRequest();
        for (Object arg : args) {
            if (arg instanceof FileParamBO) {
                FileParamBO param = (FileParamBO)arg;
                FileHeaderBO fileHeader = param.getFileHeader();
                if (fileHeader == null) {
                    if (request == null) {
                        fileHeader = FileHeaderBO.builder().build();
                    } else {
                        fileHeader = FileHeaderBO.builder().ip(IpUtil.getIp(request))
                            .referer(request.getHeader(HttpHeaders.REFERER))
                            .ua(request.getHeader(HttpHeaders.USER_AGENT)).build();
                    }
                    param.setFileHeader(fileHeader);
                }
            }
        }
    }
}
